package com.dao.impl;

// default package

import static org.hibernate.criterion.Example.create;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.dao.PaperDao;
import com.model.Paper;
import com.model.User;
import com.util.CompareTime;
import com.util.Pagination;
import com.util.Paperjson;
import com.util.QueryTerm;

@Repository("paperDao")
public class PaperDaoImpl implements PaperDao {
    @Resource
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void save(Paper transientInstance) {
        try {
            Session session = sessionFactory.getCurrentSession();
            session.save(transientInstance);
        } catch (RuntimeException re) {
            throw re;
        }

    }

    @Override
    public void delete(Paper persistentInstance) {
        try {
            Session session = sessionFactory.getCurrentSession();
            session.beginTransaction();
            session.delete(persistentInstance);
            session.getTransaction().commit();
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public Paper findById(java.lang.Integer id) {
        try {
            Session session = sessionFactory.getCurrentSession();
            Query q = session.createQuery("from Paper p where p.id = " + id);
            // Paper instance = (Paper) session
            // .get("com.model.Paper", id);
            return (Paper) q.list().get(0);
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public List<Paper> findByExample(Paper instance) {
        try {
            Session session = sessionFactory.getCurrentSession();
            List<Paper> results = session.createCriteria("com.model.Paper").add(create(instance)).list();
            return results;
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public List findAll() {
        try {
            Session session = sessionFactory.getCurrentSession();
            String queryString = "from Paper p order by p.begintime desc";
            Query queryObject = session.createQuery(queryString);
            return queryObject.list();
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public Paper merge(Paper detachedInstance) {
        try {
            Session session = sessionFactory.getCurrentSession();
            Paper result = (Paper) session.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            throw re;
        }
    }

    @Override
    public Pagination getPaperList(Paper paper, Pagination page) {
        Session session = sessionFactory.getCurrentSession();
        // Criteria criteria = session.createCriteria("com.model.Paper");
        // if(paper.getPapername()!=null)
        // criteria.add( Restrictions.like("papername",
        // "%"+paper.getPapername()+"%"));
        // if(paper.getIsjava()!=null)
        // criteria.add(Restrictions.eq("isjava",
        // paper.getIsjava()));//((page.getCurrentpage()-1)*page.getPagesize())+page.getPagesize()
        //
        // criteria.setFirstResult((page.getCurrentpage()-1)*page.getPagesize()).setMaxResults(10).addOrder(Order.desc("begintime"));
        String name = paper.getPapername();
        String isjava = paper.getIsjava();
        if (name == null || isjava == null) {
            name = "";
            isjava = "";
        }

        String hql = "from Paper p where p.papername like '%" + name + "%' and p.isjava like '%" + isjava + "%' order by p.begintime desc ";
        Query query = session.createQuery(hql);
        page.setTotal(query.list().size());
        query.setFirstResult((page.getCurrentpage() - 1) * page.getPagesize());
        query.setMaxResults(30);
        page.setTotalpagecountByhand();
        page.setList(query.list());
        return page;
    }

    // 用于分页查询
    @Override
    public Pagination queryForPage(QueryTerm query) {
        int index = query.getIndex();
        String hql = "from Paper";
        int status = toStatus(query.getStatus()); // 默认为-1 即为选择状态
        String javaoc = "";
        if (query.getIsjava().equals("java")) {
            javaoc = "0";
        }
        if (query.getIsjava().equals("c")) {
            javaoc = "1";
        }

        if (query.getTeacherOrexam().equals("teacher")) { // 当选择为老师时
            int tid = findTeacherId(query.getSelectOne());
            if (tid != -1) { // 该老师名称存在时
                hql = toQuery(tid, status, javaoc, "");
            } else {
                hql = toQuery(-1, status, javaoc, "");
            }
        } else if (query.getTeacherOrexam().equals("exam")) { // 当选择为卷子名称时
            hql = toQuery(-1, status, javaoc, query.getSelectOne());
        } else if (query.getTeacherOrexam().equals("")) {
            if (query.getIsjava().equals("") && query.getSelectOne().equals("") && query.getStatus().equals("") && query.getTeacherOrexam().equals("")) { // 用于无条件显示
                hql = "from Paper p where p.isvisible = 1 order by p.begintime desc ";
            } else {
                hql = toQuery(-1, status, javaoc, "");
            }
        }
        Session session = sessionFactory.getCurrentSession();
        Query querypage = session.createQuery(hql);
        Pagination page = new Pagination(index, 30); // query.getIndex() 表示当前第几页
        int size = querypage.list().size();
        page.setTotal(size); // 设置总共多少条记录
        page.setTotalpagecountByhand(); // 设置一共多少页
        querypage.setFirstResult((page.getCurrentpage() - 1) * page.getPagesize());
        querypage.setMaxResults(30); // 一页显示10条数据

        CompareTime comparaTime = new CompareTime(); // 打印状态
        List list = new ArrayList();

        for (int i = 0; i < querypage.list().size(); i++) {
            Paper p = (Paper) querypage.list().get(i);

            if (p.getBegintime() != null && p.getEndtime() != null) {
                p.setStatus(comparaTime.compareToTime(p.getBegintime(), p.getEndtime()));
            } else {
                p.setStatus("forever");
            }
            Paperjson pjson = new Paperjson(p.getId(), p.getPapername(), p.getIsjava(), p.getBegintime(), p.getEndtime(), p.getIsvisible(), p.getStatus(), p.getUser().getUsername());
            list.add(pjson);
        }
        page.setList(list);
        return page;
    }

    public int findTeacherId(String tname) {
        if (tname.equals("")) {
            return -1;
        } else {
            String hql = " from User u where u.username like '%" + tname + "%'" + " and  u.role = 1";
            Session session = sessionFactory.getCurrentSession();
            Query query = session.createQuery(hql);

            if (!query.list().isEmpty()) {

                User u = (User) query.list().get(0);
                return u.getId();
            } else {
                return -1;
            }
        }

    }

    public String toQuery(int tid, int status, String javaoc, String examname) { // 1.老师ID
                                                                                 // 2.选择的状态
                                                                                 // 3.考试类型
                                                                                 // java0
                                                                                 // c1
                                                                                 // 4.考试名称
        String hql = "";
        Timestamp timestamp = new java.sql.Timestamp(new java.util.Date().getTime());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowtime = formatter.format(timestamp);

        timestamp.toString();
        if (tid != -1) {
            switch (status) {
            case (0):
                hql = "from Paper p where p.isvisible = 1 and p.user.id=" + tid + " and p.isjava like '%" + javaoc + "%'" + " order by p.begintime desc";
                break;
            case (1):
                hql = "from Paper p where p.isvisible = 1 and p.user.id=" + tid + " and p.isjava like '%" + javaoc + "%' and p.begintime < '" + nowtime + "' and p.endtime > '" + nowtime + "'" + " order by p.begintime desc";
                break;
            case (2):
                hql = "from Paper p where p.isvisible = 1 and p.user.id=" + tid + " and p.isjava like '%" + javaoc + "%' and p.endtime < '" + nowtime + "'" + " order by p.begintime desc";
                break;
            case (3):
                hql = "from Paper p where p.isvisible = 1 and p.user.id=" + tid + " and p.isjava like '%" + javaoc + "%' and p.begintime is null" + " order by p.begintime desc"; // forever
                                                                                                                                                                                  // 没有时间的
                break;
            case (4):
                hql = "from Paper p where p.isvisible = 1 and p.user.id=" + tid + " and p.isjava like '%" + javaoc + "%' and p.begintime >'" + nowtime + "'" + " order by p.begintime desc";
                break;
            case (-1):
                hql = "from Paper p where p.isvisible = 1 and p.user.id=" + tid + " and p.isjava like '%" + javaoc + "%'" + " order by p.begintime desc";
                break;
            }
        } else if (tid == -1) {
            switch (status) {
            case (0):
                hql = "from Paper p where p.isvisible = 1 and p.papername like '%" + examname + "%' and p.isjava like '%" + javaoc + "%'" + " order by p.begintime desc";
                break;
            case (1):
                hql = "from Paper p where p.isvisible = 1 and p.papername like '%" + examname + "%' and p.isjava like '%" + javaoc + "%' and p.begintime < '" + nowtime + "' and p.endtime > '" + nowtime + "'" + " order by p.begintime desc";
                break;
            case (2):
                hql = "from Paper p where p.isvisible = 1 and p.papername like '%" + examname + "%' and p.isjava like '%" + javaoc + "%' and p.endtime < '" + nowtime + "'" + " order by p.begintime desc";
                break;
            case (3):
                hql = "from Paper p where p.isvisible = 1 and p.papername like '%" + examname + "%' and p.isjava like '%" + javaoc + "%' and p.begintime is null" + " order by p.begintime desc";
                break;
            case (4):
                hql = "from Paper p where p.isvisible = 1 and p.papername like '%" + examname + "%' and p.isjava like '%" + javaoc + "%' and p.begintime > '" + nowtime + "'" + " order by p.begintime desc";
                break;
            case (-1):
                hql = "from Paper p where p.isvisible = 1 and p.papername like '%" + examname + "%' and p.isjava like '%" + javaoc + "%'" + " order by p.begintime desc";
                break;
            }
        }
        return hql;
    }

    public int toStatus(String status) { // 考试状态转换 没选时为 -1
        int sta = -1;
        if (status.equals("all")) {
            sta = 0;
            return sta;
        }
        if (status.equals("running")) {
            sta = 1;
            return sta;
        }
        if (status.equals("pass")) {
            sta = 2;
            return sta;
        }
        if (status.equals("forever")) {
            sta = 3;
            return sta;
        }
        if (status.equals("waiting")) {
            sta = 4;
            return sta;
        } else {
            return sta;
        }

    }

    @Override
    public int countPaper() {
        Session session = sessionFactory.getCurrentSession();
        Query q = session.createQuery("from Paper ");
        List<Paper> l = q.list();

        if (l.size() == 0) {
            return 0;
        } else {
            return l.get(l.size() - 1).getId();
        }

    }

    @Override
    public int SumPaper() {
        Session session = sessionFactory.getCurrentSession();
        Query q = session.createQuery("from Paper ");
        List<Paper> l = q.list();
        return l.size() == 0 ? 0 : l.size();
    }

    @Override
    public boolean checkpw(String password, int pid) {
        boolean flag = false;
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Paper p where p.paperpw='" + password + "' and p.id = " + pid;
        Query q = session.createQuery(hql);
        if (!q.list().isEmpty()) {
            flag = true;
        }
        return flag;
    }

    @Override
    public List showPaperScore(int uid) {

        List list;
        Session session = sessionFactory.getCurrentSession();
        String hql = "select pro.paper.id, pro.paper.papername, pro.paper.isjava,sum(pro.score) from Proanswer pro " +
        		"where UNIX_TIMESTAMP(pro.paper.endtime) < UNIX_TIMESTAMP(NOW()) and pro.user.id=" + uid + " group by pro.paper.id ";

        Query q = session.createQuery(hql);
        list = q.list();
        return list;

    }

    @Override
    public Pagination getMyPaperList(Paper paper, Pagination page) {
        Session session = sessionFactory.getCurrentSession();
        String name = paper.getPapername();
        String isjava = paper.getIsjava();
        if (name == null || isjava == null) {
            name = "";
            isjava = "";
        }

        String hql = "from Paper p where p.papername like '%" + name + "%' and p.isjava like '%" + isjava + "%' and p.user.id = " + paper.getUser().getId() + "  order by p.begintime desc ";
        Query query = session.createQuery(hql);
        page.setTotal(query.list().size());
        query.setFirstResult((page.getCurrentpage() - 1) * page.getPagesize());
        query.setMaxResults(30);
        page.setTotalpagecountByhand();
        page.setList(query.list());
        return page;
    }

    @Override
    public void deletePaperProgram(String paperid, String id) {
        Session session = sessionFactory.getCurrentSession();
        String sql = "delete from db_paperprogram where paperid = " + paperid + " and programid = " + id;
        session.createSQLQuery(sql).executeUpdate();

    }

    @Override
    public void paperDel(int id) {
        Session session = sessionFactory.getCurrentSession();
        session.createQuery("delete from Paper p where p.id=" + id).executeUpdate();

    }

    @Override
    public void PaperEditInfo(Paper paper) {
        Paper p = findById(paper.getId());
        Session session = sessionFactory.getCurrentSession();
        p.setBegintime(paper.getBegintime());
        p.setEndtime(paper.getEndtime());
        p.setIsjava(paper.getIsjava());
        p.setPaperpw(paper.getPaperpw());
        p.setPapername(paper.getPapername());
        p.setRank(paper.getRank());
        Paper pold = (Paper) session.get(Paper.class, paper.getId());
        pold = p;
    }

    @Override
    public int getPaperScore(int pid) {
        Session session = sessionFactory.getCurrentSession();
        // String hql
        // ="select sum(pro.score) from Programming pro , PaperProgram pp  where pp.programming.id = pro.id and  pp.paper.id = "+pid;
        // //改句也可以查询
        String hql = "select sum(pro.score) from Paper p  join p.paperPrograms pro where  p.id = " + pid;
        Query q = session.createQuery(hql);
        List l = q.list();
        if (l.get(0) == null) {
            return 0;
        }

        Long score = (Long) l.get(0);
        return score.intValue();
    }

}